package com.pjbao.Service.util;


import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfReader;
import com.pjbao.Service.model.EmailModel;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by zero on 2016/10/19.
 */
@Configuration
@RestController
@RequestMapping("/down")
public class DownFile {

    @Value("${email.path}")
    private String emailpath;

    Logger logger = LoggerFactory.getLogger("====wechat====");


    @RequestMapping("/pdf")
    private boolean download(String birturl, String savePath) throws IOException {
        HttpClient httpClient1 = new DefaultHttpClient();
        HttpGet httpGet1 = new HttpGet(birturl);
        try {
            HttpResponse httpResponse1 = httpClient1.execute(httpGet1);

            StatusLine statusLine = httpResponse1.getStatusLine();
            if (statusLine.getStatusCode() == 200) {
                String filePath = savePath; // 文件路径
                File file = new File(filePath);
                FileOutputStream outputStream = new FileOutputStream(file);
                InputStream inputStream = httpResponse1.getEntity()
                        .getContent();
                byte b[] = new byte[2048];
                int j = 0;
                while ((j = inputStream.read(b)) != -1) {
                    outputStream.write(b, 0, j);
                }
                outputStream.flush();
                outputStream.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            httpClient1.getConnectionManager().shutdown();
        }
        return true;
    }

    @RequestMapping("/filePdf")
    public String downloadTest(EmailModel emailModel) {
        String emailresult = "";
        String content = "";
        try {
            RestTemplate restTemplate = new RestTemplate();
            String birtUrl = "http://localhost:8080/birt/frameset?__report=apiService/reportToPDF.rptdesign&__format=pdf&name=" + emailModel.getName() + "&cid=" + emailModel.getCid() + "&cardid=" + emailModel.getCardid() + "&gid=" + emailModel.getGid() + "&token=" + emailModel.getToken() + "&interface=" + emailModel.getInterfaces();
            logger.info("获取到的URL是:" + birtUrl);
            this.download(birtUrl, emailpath + emailModel.getCid() + ".pdf");
            logger.info("获取到的邮箱是:" + emailModel.getEmail());
            Map<String, String> map = new HashMap<String, String>();
            map.put("fileName", emailModel.getCid() + ".pdf");
            map.put("subject", "个人信用报告");
            //判断pdf文件是否能被正常读取
            if ("yes".equals(fileDetection(emailModel.getCid() + ".pdf"))) {
                content = "个人信用报告在附件,请注意查收!!";
            }else{
                content = "您在查询 "+emailModel.getName()+" 时,附件生成失败,请查看查询参数是否正确!";
                map.put("fileName","no");
            }
            map.put("content", content);
            restTemplate.postForObject("http://localhost:10086/dataService/email/sendMail?fileName=" + map.get("fileName") + "&subject=" + map.get("subject") + "&content=" + map.get("content") + "&receiver=" + emailModel.getEmail(), null, String.class);
            emailresult = "yes";
        } catch ( IOException e) {
            emailresult = "no";
        }

        logger.info("restTemplate返回值是:" + emailresult);

        return emailresult;
    }

    public String fileDetection(String fileName) {
        String result = "";
        try {
            if (check(emailpath + fileName)) {
                result = "yes";
            } else {
                result = "no";
            }
        } catch (Exception E) {
            result = "no";
        }

        return result;
    }


    private static boolean check(String file) {
        boolean flag1 = false;
        int n = 0;
        try {
            Document document = new Document(new PdfReader(file).getPageSize(1));
            document.open();
            PdfReader reader = new PdfReader(file);
            n = reader.getNumberOfPages();
            if (n != 0)
                flag1 = true;
            document.close();
        } catch (IOException e) {
            e.printStackTrace();

        }
        return flag1;

    }

}
